from ..database import database, ModelMixin
from peewee import *
from .member import Member
from .product import Product
from .offer import Offer
from .currency import Currency
from .deliver_info import DeliverInfo
import datetime


class Order(database.Model, ModelMixin):
    STATUS_PAID = 'paid'
    STATUS_PAY_ERROR = 'pay_error'
    id = PrimaryKeyField(db_column='id')
    description = CharField(db_column='desc', max_length=200, help_text='订单描述')
    remark = CharField(db_column='remark', max_length=450, help_text='备注', null=True)
    member = ForeignKeyField(Member, help_text='所属会员')
    status = CharField(db_column='status', max_length=20, help_text='状态', choices=(
        ('created', '已创建'),
        ('paid', '已支付'),
        ('canceled', '已取消'),
        ('ended', '已结束'),
        ('removed', '已删除'),
        ('shipped', '已送货'),
        ('shipping', '送货中'),
        ('confirmed', '已确认'),
        ('returned', '已退款'),
        ('pay_error', '支付失败')

    ),
                       default='created')
    # review_of_seller = CharField(db_column='review_of_seller', max_length=1, choices=('Y', 'N'), default='N',
    #                              help_text='卖家是否评价')
    # review_of_buyer = CharField(db_column='review_of_buyer', max_length=1, choices=('Y', 'N'), help_text='买家是否评价',
    #                             default='N')
    settlement = BooleanField(default=False)
    fee = DecimalField(db_column='fee', decimal_places=4, default=0.00)
    real_fee = DecimalField(db_column='real_fee', decimal_places=4, default=0.00, help_text='实际手续费')
    real_amount = DecimalField(db_column='real_amount', decimal_places=4, default=0.00, help_text='实际支付金额')
    amount = DecimalField(db_column='amount', decimal_places=4, default=0.00)
    discount_amount = DecimalField(db_column='discount_amount', decimal_places=4, default=0.00)
    discount_method = CharField(db_column='discount_method', max_length=30, help_text='折扣方式', default='')
    discount_code = CharField(db_column='discount_count', max_length=80, help_text='折扣代码', default='')
    payment_method = CharField(db_column='payment_method', help_text='支付方式', default='', max_length=60)
    created_at = DateTimeField(db_column='created_at', help_text='创建时间', default=datetime.datetime.now)
    updated_at = DateTimeField(db_column='updated_at', help_text='更新时间', default=datetime.datetime.now)
    payment_time = DateTimeField(db_column='payment_time', help_text='支付时间', null=True)
    expire_time = DateTimeField(db_column='expire_time', help_text='过期时间', null=True)
    settle_time = DateTimeField(db_column='settle_time', help_text='结算时间', default=datetime.datetime.now)
    currency = ForeignKeyField(Currency)
    trade_code = CharField(db_column='trade_code', help_text='交易编码')
    payment_seq = CharField(db_column='payment_seq', help_text='支付流水号', null=True)
    notify_info = CharField(db_column='notify_info', max_length=400, null=True)

    # shipp_at   = DateTimeField(db_column=)
    # real_amount = DecimalField(db_column='real_amount', decimal_places=4, default=0.00)00

    class Meta:
        # db_table = '{}_orders'.format(TABLE_PREFIX)
        only_save_dirty = True

    def is_paid(self):
        return self.status == 'paid'

    @classmethod
    def get_by_member(cls, member):
        return cls.select().where(Order.member == member)


class OrderDetail(database.Model):
    id = PrimaryKeyField(db_column='id')
    order = ForeignKeyField(Order, related_name='details')
    count = IntegerField(db_column='count', help_text='数量')
    amount = DecimalField(db_column='amount', help_text='金额', decimal_places=4, default=0.00)
    real_amount = DecimalField(db_column='real_amount', help_text='实际金额', decimal_places=4, default=0.00)
    product = ForeignKeyField(Product)
    # offer = ForeignKeyField(Offer)
    discount_amount = DecimalField(db_column='discount_amount', decimal_places=4, default=0.00)
    discount_method = CharField(db_column='discount_method', max_length=30, help_text='折扣方式', default='')
    discount_code = CharField(db_column='discount_count', max_length=80, help_text='折扣代码', default='')
    delivery_method = CharField(db_column='delivery_method', max_length='80', help_text='发货方式代码', default='ticket')
    deliver_info = ForeignKeyField(DeliverInfo, null=True)

    class Meta:
        # db_table = '{}_order_details'.format(TABLE_PREFIX)
        only_save_dirty = True


class OrderDetailExt(database.Model):
    id = PrimaryKeyField(db_column='id')
    order_detail = ForeignKeyField(OrderDetail, related_name='detail_exts')
    count = IntegerField(db_column='count', help_text='数量')
    amount = DecimalField(db_column='amount', help_text='金额')
    ext_code = CharField(db_column='ext_code', help_text='附加项代码', max_length=40)
    ext_type = CharField(db_column='ext_type', help_text='附加加类型', max_length=40)

    class Meta:
        only_save_dirty = True

        # db_table = '{}_order_detail_exts'.format(TABLE_PREFIX)

# TODO
# @Order.pre_save
# def order_pre_save_handler(instance, created):
#     if created and instance.id is None:
#         from .table_seq import TableSeq
#         meta = getattr(instance, '_meta')
#         if meta:
#             code = getattr(meta, 'db_table') or 'order'
#             instance.id = TableSeq.get_seq(code)
#             instance.trade_code = '{}-{}'.format(
#                 instance.id,
#                 datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
#             instance.desc = '{} #{}'.format('快搜游戏订单 ', instance.id)
